import Vue from 'vue'
import VueRouter from 'vue-router'
import index from '../views/Index.vue'
import store from '../store' //导入vuex 对象

Vue.use(VueRouter)


//路由表
const routes = [
  {
    path: '/', name: 'index', component: index,
    //子路由
    children: [
      { path: '/users', name: 'users', component: () => import('../views/system/Users.vue') },
      { path: '/Index', name: 'Index', component: () => import('../views/goods/Index.vue') },
      { path: '/Menus', name: 'Menus', component: () => import('../views/Menus/Menus.vue') },
      { path: '/Control', name: 'Control', component: () => import('../views/Control/index.vue') },
      { path: '/sale', name: 'sale', component: () => import('../views/outside/sale.vue') },
      { path: '/Pshop', name: 'Pshop', component: () => import('../views/Pmessage/Pshop.vue') },
      { path: '/Personal', name: 'Personal', component: () => import('../views/Personal/Personal.vue') },
      { path: '/Porder', name: 'porder', component: () => import('../views/Pmessage/Porder.vue') },
      { path: '/DDmanage', name: 'DDmanage', component: () => import('../views/Pmessage/DDmanage.vue') },
      { path: '/order', name: 'order', component: () => import('../views/outside/order.vue') },
      { path: '/Customer', name: 'Customer', component: () => import('../views/Customer/Customer.vue') },
      { path: '/GoodControl', name: 'GoodControl', component: () => import('../views/GoodControl/index.vue') },
      { path: '/Roles', name: 'Roles', component: () => import('../views/Roles/Roles.vue') },
    ]
  },
  { path: '/login', name: 'login', component: () => import('../views/Login.vue') },
]

//实例 路由对象
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes  //路由表
})

//路由导航守卫 
router.beforeEach((to, from, next) => {
  // console.log('to: ', to);
  // console.log('from: ', from);

  if (store.state.user && store.state.user.Token.length > 0 || to.path == '/login') {
    next();
  } 
  else {
    if (sessionStorage.getItem('user') != null) {
      //将预留的信息 保存到 vuex 中去
      store.commit('setUser', JSON.parse(sessionStorage.getItem('user')));
      next();
    } else {
      router.push('/login');
    }

  }
})

export default router 
